var server = window.location.host; //$("#server").val();
$("#server").val(server);
var full_ctx = "http://" + server;
// 页面加载后，需要做的
$().ready(function () {
	tt.vf.req.addId("tt_method", "templateName", "tt_request_url");
});

var urlFormObj = document.getElementById("urlForm");
function getHtml(formId) {
	if (!tt.validateId('tt_request_url')) {
		return;
	}

	$.ajax({
		url: full_ctx + "/common/httpclient/getHtml.talent",
		data: $("#" + formId).serialize(),
		type: "POST",
		dataType: "jsonp",
		jsonp: "tio_http_jsonp",
		scriptCharset: 'UTF-8',
		cache: false,

		success: function (retObj) {
			// tt_complete();
			// var retObj = JSON.parse(_data.responseText);
			var result = tt_showResult(retObj);
			if (result) {
				var ss = retObj.data;
				var isJson = false;
				try {
					if (!talent_isSpecifiedType(ss, "String")) {
						ss = JSON.stringify(retObj.data);

					}
				} catch (e) {
					ss = retObj.data;
				}

				document.getElementById("html_container").innerHTML = ss;
				document.getElementById("response_div").style.display = "";

				// 格式化显示
				var container = document
					.getElementById("html_container_json");
				container.innerHTML = "";
				try {
					var json = JSON.parse(ss);
					var jsonString = JsonUti.convertToString(json);
					showCode(jsonString, container);
				} catch (e) {
					console.log(e);
					container.innerHTML = ss;

				}
			}
		}
	});
}



function generateOfflineData() {
	$.ajax({
		url: full_ctx + "/common/httpclient/generateOfflineData.talent",
		type: "GET",
		dataType: "jsonp",
		jsonp: "tio_http_jsonp",
		scriptCharset: 'UTF-8',
		cache: false,

		success: function (retObj) {
			var result = tt_showResult(retObj, false);
			if (result) {
				layer.msg('离线文档生成成功');
			} else {
				//alert("保存失败");
			}
		}
	});
}


function showCode(str, co) {
	// var codeDiv = document.createElement("div");
	var codeAera = document.createElement("pre");

	// codeAera.name = "code";
	// codeAera.setAttribute('name', 'code'); // ff下须如此

	codeAera.className = "brush: js;";
	// codeAera.id = 'script_div';

	// co.appendChild(codeDiv);
	co.appendChild(codeAera);

	codeAera.innerHTML = str;
	console.log(SyntaxHighlighter.highlight);
	SyntaxHighlighter.highlight();
}

function formatJson(jsonStr) {
	return jsonStr;
}

function getCookie(formId) {
	if (!tt.validateId('tt_request_url')) {
		return;
	}
	$.ajax({
		url: full_ctx + "/common/httpclient/getCookie.talent",
		data: $("#" + formId).serialize(),
		type: "POST",
		dataType: "jsonp",
		jsonp: "tio_http_jsonp",
		scriptCharset: 'UTF-8',
		cache: false,

		success: function (retObj) {
			var result = tt_showResult(retObj);
			if (result) {
				var cookieEs = document.getElementsByName("cookies");
				for (var i = 0; i < cookieEs.length; i++) {
					cookieEs[i].value = "";
				}

				if (retObj.data) {
					for (var i = 0; i < retObj.data.length; i++) {
						cookieEs[i].value = retObj.data[i];
						cookieEs[i + 1].value = retObj.data[i];
					}
				}
			}
		}
	});
}

function loadTemplate(formId, templateAbsPath) {
	if (!tt.validateId('templateName')) {
		return;
	}

	document.getElementById("response_div").style.display = "none";

	var _data = null;
	if (formId) {
		_data = $("#" + formId).serialize();
	} else {
		_data = {
			"templateAbsPath": templateAbsPath
		};
	}
	$.ajax({
		url: full_ctx + "/common/httpclient/loadTemplate.talent",
		data: _data,
		type: "POST",
		dataType: "jsonp",
		jsonp: "tio_http_jsonp",
		scriptCharset: 'UTF-8',
		cache: false,

		success: function (retObj) {

			var result = tt_showResult(retObj);
			if (result) {
				fillWithJsonData(JSON.parse(retObj.data));
			}
		}
	});
}

function saveTemplate(formId) {
	if (!tt.validateId('templateName')) {
		return;
	}

	var html_container_value = document.getElementById("html_container").innerHTML;
	var _data = $("#" + formId).serialize();
	if (html_container_value) {
		_data = "resp_demo=" + encodeURIComponent(html_container_value) + "&"
			+ _data;
	}

	console.log(_data);
	if (confirm("确定保存?")) {
		$.ajax({
			url: full_ctx + "/common/httpclient/saveTemplate.talent",
			data: _data,
			type: "POST",
			dataType: "jsonp",
			jsonp: "tio_http_jsonp",
			scriptCharset: 'UTF-8',
			cache: false,

			success: function (retObj) {
				var result = tt_showResult(retObj, false);
				if (result) {
					try {
						loadAllTemplate(function (zTreeObj) {
							var id = document.getElementById("templateName").value;
							var node = zTreeObj.getNodeByParam("id", id, null);
							zTreeObj.selectNode(node);
							// loadTemplate(null, node.id);
						});
					} catch (e) {
						console.log(e);
					}
				}
			}
		});
	}
}

function renameTemplate() {
	var _data = {};
	var templateName = document.getElementById("templateName").value;
	_data["newTemplateAbsPath"] = templateName;

	var zTree = $.fn.zTree.getZTreeObj("menuTree");
	if (!zTree) {
		return;
	}
	var nodes = zTree.getSelectedNodes();

	if (nodes == null || nodes.length == 0) {
		alert("没有选中任何模板，没法重命名");
		return;
	}
	var node = nodes[0];
	_data["oldTemplateAbsPath"] = node.id;

	$.ajax({
		url: full_ctx + "/common/httpclient/renameTemplate.talent",
		data: _data,
		type: "POST",
		dataType: "jsonp",
		jsonp: "tio_http_jsonp",
		scriptCharset: 'UTF-8',
		cache: false,
		success: function (retObj) {
			var result = tt_showResult(retObj);
			if (result) {
				loadAllTemplate(function (zTreeObj) {
					var nodes = zTree
						.getNodesByParam(
							"id",
							document.getElementById("templateName").value,
							null);
					if (nodes && nodes.length > 0) {
						zTreeObj.selectNode(nodes[0]);
						loadTemplate(null, nodes[0].id);
					}
				});
			}
		}
	});

}

function deleteTemplate() {
	if (confirm("确定删除?")) {
		var _data = {};
		var templateName = document.getElementById("templateName").value;
		_data["templateName"] = templateName;
		_data["isAbspath"] = true;

		var zTree = $.fn.zTree.getZTreeObj("menuTree");
		if (!zTree) {
			return;
		}
		var nodes = zTree.getNodesByParam("id", templateName, null);
		if (nodes == null || nodes.length == 0) {
			alert("没有选中任何模板，没法删除");
			return;
		}
		var node = nodes[0];

		var nextSelectnode = node.getPreNode();
		if (!nextSelectnode) {
			nextSelectnode = node.getNextNode();
		}
		var nextSelectedId = null;
		if (nextSelectnode) {
			nextSelectedId = nextSelectnode.id;
		}

		$.ajax({
			url: full_ctx + "/common/httpclient/deleteTemplate.talent",
			data: _data,
			type: "POST",
			dataType: "jsonp",
			jsonp: "tio_http_jsonp",
			scriptCharset: 'UTF-8',
			cache: false,
			success: function (retObj) {
				var result = tt_showResult(retObj);
				if (result) {
					loadAllTemplate(function (zTreeObj) {
						document.getElementById("templateName").value = "";
						if (nextSelectedId) {
							if (!nextSelectnode.isdir) {
								document.getElementById("templateName").value = nextSelectedId;
								var nodes = zTreeObj
									.getNodesByParam(
										"id",
										document
											.getElementById("templateName").value,
										null);

								if (nodes && nodes.length > 0) {
									zTreeObj.selectNode(nodes[0]);
									loadTemplate(null, nodes[0].id);
								}
							}
						}
					});
				}
			}
		});
	}
}

var idIndex = 0;

/**
 * 
 * @param {}
 *            jsonData
 */
function fillWithJsonData(jsonData) {
	document.getElementById("tt_request_url").value = jsonData.url;
	document.getElementById("tt_remark").value = "";
	removeField('headerTable', 'headerTableBody', 'header', true);
	removeField('fieldTable', 'fieldTableBody', 'param', true);
	removeField('respremarkTable', 'respremarkTableBody', 'respremark', true);

	talent_c_setInputValueWithDataObj(jsonData, "", "", document
		.getElementById("urlForm"));

	var requestHeaders = jsonData.requestHeaders;
	if (requestHeaders) {
		for (var i in requestHeaders) {
			var h = requestHeaders[i];
			if (talent_isSpecifiedType(h, "String")) {
				addField('headerTable', 'headerTableBody', 'header', i, h,
					null, full_ctx
					+ '/app-res/common/httpclient/httpHeaders.json');
			} else if (talent_isSpecifiedType(h, "Array")) {
				for (var k = 0; k < h.length; k++) {
					addField(
						'headerTable',
						'headerTableBody',
						'header',
						i,
						h[k].value,
						h[k].remark,
						full_ctx
						+ '/app-res/common/httpclient/httpHeaders.json');
				}
			} else {
				addField('headerTable', 'headerTableBody', 'header', i,
					h.value, h.remark, full_ctx
					+ '/app-res/common/httpclient/httpHeaders.json');
			}

		}
	}

	var requestParams = jsonData.requestParams;
	if (requestParams) {
		for (var i in requestParams) {
			var p = requestParams[i];
			var isArray = talent_isSpecifiedType(p, "Array");
			if (isArray) {
				for (var j = 0; j < p.length; j++) {
					var pv = p[j];
					if (talent_isSpecifiedType(pv, "String")) {
						addField('fieldTable', 'fieldTableBody', 'param', i, pv);
					} else if (talent_isSpecifiedType(pv, "Array")) {
						for (var k = 0; k < pv.length; k++) {
							addField('fieldTable', 'fieldTableBody', 'param',
								i, pv[k].value, pv[k].remark);
						}
					} else {
						addField('fieldTable', 'fieldTableBody', 'param', i,
							pv.value, pv.remark);
					}

				}
			} else {
				if (talent_isSpecifiedType(p, "String")) {
					addField('fieldTable', 'fieldTableBody', 'param', i, p);
				} else if (talent_isSpecifiedType(p, "Array")) {
					for (var k = 0; k < p.length; k++) {
						addField('fieldTable', 'fieldTableBody', 'param', i,
							p[k].value, p[k].remark);
					}
				} else {
					addField('fieldTable', 'fieldTableBody', 'param', i,
						p.value, p.remark);
				}

			}
		}
	}

	var respremark = jsonData.respremark;
	if (respremark) {
		for (var i in respremark) {
			var p = respremark[i];
			var isArray = talent_isSpecifiedType(p, "Array");
			if (isArray) {
				for (var j = 0; j < p.length; j++) {
					var pv = p[j];
					if (talent_isSpecifiedType(pv, "String")) {
						addField('respremarkTable', 'respremarkTableBody',
							'respremark', i, pv);
					} else if (talent_isSpecifiedType(pv, "Array")) {
						for (var k = 0; k < pv.length; k++) {
							addField('fieldTable', 'fieldTableBody', 'param',
								i, pv[k].value, pv[k].remark);
						}
					} else {
						addField('respremarkTable', 'respremarkTableBody',
							'respremark', i, pv.value, pv.remark);
					}

				}
			} else {
				if (talent_isSpecifiedType(p, "String")) {
					addField('respremarkTable', 'respremarkTableBody',
						'respremark', i, p);
				} else if (talent_isSpecifiedType(p, "Array")) {
					for (var k = 0; k < p.length; k++) {
						addField('fieldTable', 'fieldTableBody', 'param', i,
							p[k].value, p[k].remark);
					}
				} else {
					addField('respremarkTable', 'respremarkTableBody',
						'respremark', i, p.value, p.remark);
				}

			}
		}
	}

}

// addField('headerTable', 'headerTableBody', 'header', '', '',
// '${ctx}/app-res/common/httpclient/httpHeaders.json');
// addField('fieldTable', 'fieldTableBody', 'param');
function addField(tableId, tableBodyId, prefix, nameValue, valueValue,
	remarkValue, autoCompleteUrl) {

	if (autoCompleteUrl == 1) {
		autoCompleteUrl = full_ctx
			+ '/app-res/common/httpclient/httpHeaders.json';
	}

	var tableBody = document.getElementById(tableBodyId);
	var row = tableBody.insertRow(tableBody.rows.length);

	var cell = document.createElement("td");
	row.appendChild(cell);
	var inputEle3 = talent.Util.createInputElement("checkbox");
	cell.appendChild(inputEle3);

	cell = document.createElement("td");// theadRow.insertCell(theadRow.cells.length);
	row.appendChild(cell);
	var inputEle1 = talent.Util.createInputElement("text");
	cell.appendChild(inputEle1);
	inputEle1.setAttribute("name", prefix + "_name");
	inputEle1.style.width = "100px";
	inputEle1.value = nameValue ? nameValue : "";
	inputEle1.id = "name__ujh" + idIndex++;

	cell = document.createElement("td");// theadRow.insertCell(theadRow.cells.length);
	row.appendChild(cell);
	var inputEle2 = talent.Util.createInputElement("text");
	cell.appendChild(inputEle2);
	inputEle2.setAttribute("name", prefix + "_value");
	inputEle2.style.width = "400px";
	inputEle2.value = valueValue ? valueValue : "";
	inputEle2.id = "value__ujh" + idIndex++;

	cell = document.createElement("td");// theadRow.insertCell(theadRow.cells.length);
	row.appendChild(cell);
	var inputEle3 = talent.Util.createInputElement("text");
	cell.appendChild(inputEle3);
	inputEle3.setAttribute("name", prefix + "_remark");
	inputEle3.style.width = "800px";
	inputEle3.value = remarkValue ? remarkValue : "";
	inputEle3.id = "remark__ujh" + idIndex++;

	// /
	if (autoCompleteUrl) {
		var _fields = [{
			name: 'name',
			label: 'header'
		}, {
			name: 'remark',
			label: 'remark'
		}];
		var mapping = {};
		mapping[inputEle1.id] = "name";
		mapping[inputEle2.id] = "remark";

		var autocompleteConfig = {
			url: autoCompleteUrl,
			containerid: "autocompleteContainer1",
			inputObj: inputEle1,
			// events:["mouseover"],
			contextpath: full_ctx,
			skipValidate: true,
			ajaxConfig: {
				useCache: true
			},
			fields: _fields,
			isPagination: false,
			// formid: "addForm",
			showHeader: true, // 是否显示头
			countofstartquery: 0, // 必须要输入多少个字符才开始查询
			title: "", // 如果有值将会代替框架默认的title
			styles: {
				width: "800px"
			},
			gridConfig: {
				pageSize: 20,
				colorStyle: "red"
			},
			"mapping": mapping
			// 用于
		};
		tt_autoeompleteSetup(autocompleteConfig);
		// inputEle1.fireEvent('');
	}

}

// removeField('headerTable', 'headerTableBody', 'header');
// removeField('fieldTable', 'fieldTableBody', 'param');
function removeField(tableId, tableBodyId, prefix, deleteAll) {
	var table = document.getElementById(tableBodyId);

	var rowCount = table.rows.length;
	for (var i = 0; i < rowCount; i++) {
		var row = table.rows[i];

		if (row.cells[0]) {
			var chkbox = row.cells[0].childNodes[0];
			if (deleteAll || (null != chkbox && true == chkbox.checked)) {
				table.deleteRow(i);
				rowCount--;
				i--;
			}
		}
	}
}

var OperHandler = function (config) {
	/**
	 * 删除数据
	 */
	this.del = function () {
		deleteTemplate('urlForm', config);
	};

};

function operRender(conf) {

}

var operField = {
	name: "oper",
	label: "操作",
	dataCellRenderConfig: {
		clazz: function (conf) {
			var operHandler = new OperHandler(conf);
			var delLink = tt_createGridDelBtn(conf.cell);

			talent.Util.addEventHandler(delLink, "click", operHandler.del);
		}
	}
};

function templateNameAutoeompleteSetup() {
	var inputEle = document.getElementById("templateName");
	var _fields = [{
		name: 'name',
		label: '模板名字',
		dataCellStyle: {
			textAlign: "left",
			paddingLeft: "5px"
		}
	}, {
		name: 'date',
		label: '创建日期'
	}, operField];
	var mapping = {};
	mapping["templateName"] = "name";

	var autocompleteConfig1 = {
		url: full_ctx + "/common/httpclient/getTemplateList.talent",
		containerid: "autocompleteContainer",
		inputObj: inputEle,
		contextpath: full_ctx,
		skipValidate: true,
		events: ["click"],
		formid: "urlForm",
		callback: function (record) {
			loadTemplate('urlForm');
		},
		ajaxConfig: {
			useCache: true
		},
		fields: _fields,
		isPagination: true,
		gridConfig: {
			pageSize: 20,
			colorStyle: "red"
		},
		// formid: "addForm",
		showHeader: false, // 是否显示头
		countofstartquery: 0, // 必须要输入多少个字符才开始查询
		title: "", // 如果有值将会代替框架默认的title
		styles: {
			width: "800px"
		},
		"mapping": mapping
		// 用于
	};
	tt_autoeompleteSetup(autocompleteConfig1);
}
// templateNameAutoeompleteSetup();

var JsonUti = {
	// 定义换行符
	n: "\n",
	// 定义制表符
	t: "\t",
	// 转换String
	convertToString: function (obj) {
		return JsonUti.__writeObj(obj, 1);
	},
	// 写对象
	__writeObj: function (obj // 对象
		, level // 层次（基数为1）
		, isInArray) { // 此对象是否在一个集合内
		// 如果为空，直接输出null
		if (obj == null) {
			return "null";
		}
		// 为普通类型，直接输出值
		if (obj.constructor == Number || obj.constructor == Date
			|| obj.constructor == String || obj.constructor == Boolean) {
			var v = obj.toString();
			var tab = isInArray
				? JsonUti.__repeatStr(JsonUti.t, level - 1)
				: "";
			if (obj.constructor == String || obj.constructor == Date) {
				// 时间格式化只是单纯输出字符串，而不是Date对象
				return tab + ("\"" + v + "\"");
			} else if (obj.constructor == Boolean) {
				return tab + v.toLowerCase();
			} else {
				return tab + (v);
			}
		}
		// 写Json对象，缓存字符串
		var currentObjStrings = [];
		// 遍历属性
		for (var name in obj) {
			var temp = [];
			// 格式化Tab
			var paddingTab = JsonUti.__repeatStr(JsonUti.t, level);
			temp.push(paddingTab);
			// 写出属性名
			temp.push("\"" + name + "\" : ");
			var val = obj[name];
			if (val == null) {
				temp.push("null");
			} else {
				var c = val.constructor;
				if (c == Array) { // 如果为集合，循环内部对象
					temp.push(JsonUti.n + paddingTab + "[" + JsonUti.n);
					var levelUp = level + 2; // 层级+2
					var tempArrValue = []; // 集合元素相关字符串缓存片段
					for (var i = 0; i < val.length; i++) {
						// 递归写对象
						tempArrValue.push(JsonUti.__writeObj(val[i], levelUp,
							true));
					}
					temp.push(tempArrValue.join("," + JsonUti.n));
					temp.push(JsonUti.n + paddingTab + "]");
				} else if (c == Function) {
					temp.push("[Function]");
				} else {
					// 递归写对象
					temp.push(JsonUti.__writeObj(val, level + 1));
				}
			}
			// 加入当前对象“属性”字符串
			currentObjStrings.push(temp.join(""));
		}
		return (level > 1 && !isInArray ? JsonUti.n : "") // 如果Json对象是内部，就要换行格式化
			+ JsonUti.__repeatStr(JsonUti.t, level - 1) + "{" + JsonUti.n // 加层次Tab格式化
			+ currentObjStrings.join("," + JsonUti.n) // 串联所有属性值
			+ JsonUti.n + JsonUti.__repeatStr(JsonUti.t, level - 1) + "}"; // 封闭对象
	},
	__isArray: function (obj) {
		if (obj) {
			return obj.constructor == Array;
		}
		return false;
	},
	__repeatStr: function (str, times) {
		var newStr = [];
		if (times > 0) {
			for (var i = 0; i < times; i++) {
				newStr.push(str);
			}
		}
		return newStr.join("");
	}
};

var setting = {
	view: {
		// addHoverDom : treeNodeAddHoverDom,
		// removeHoverDom : treeNodeRemoveHoverDom,
		selectedMulti: false,
		nameIsHTML: true,
		showLine: true,
		showTitle: true,
		showIcon: false
	},

	edit: {
		// enable : true
	},

	data: {
		simpleData: {
			enable: true,
			pIdKey: "pId"
		}
	},
	callback: {
		// onRightClick : myOnRightClick,
		onClick: treeNodeClicked
	}
};

function treeNodeClicked(event, treeId, treeNode, clickFlag) {
	if (!treeNode.isdir) {
		// var server = $('#server').combobox('getValue');
		openTab(treeNode.name, "./httpclient2.html?id=" + encodeURIComponent(treeNode.id) + "&server=" + encodeURIComponent(server), treeNode.id, null, true);


		//		document.getElementById("templateName").value = treeNode.id;
		//		loadTemplate(null, treeNode.id);
	}
}
var zTreeObj;
function loadAllTemplate(callback) {
	// server = $('#server').combobox('getValue');
	full_ctx = "http://" + server;

	var url = full_ctx
		+ "/common/httpclient/getTemplateTree.talent?isContainData=true";
	$.ajax({
		url: url,
		type: "GET",
		dataType: "jsonp",
		jsonp: "tio_http_jsonp",
		cache: false,
		success: function (resp) {
			var isOk = tt_showResult(resp, false);
			if (isOk) {
				// var treedata = convertData(resp.data, server);
				// console.log(resp.data);
				zTreeObj = $.fn.zTree.init($("#menuTree"), setting,
					resp.data);
				zTreeObj.expandNode(getRoot(), true, false, true);
				if (selectedNodes && selectedNodes.length > 0) {
					for (var i = 0; i < selectedNodes.length; i++) {
						zTreeObj.selectNode(selectedNodes[i]);
						// document.getElementById("templateName").value
						// = "";
						// treeNodeClicked(null, null, selectedNodes[i],
						// null);
					}
				}

				if (callback) {
					callback.call(callback, zTreeObj);
				}
			}
		}
	});
}

function getRoot() {
	var treeObj = $.fn.zTree.getZTreeObj("menuTree");
	// 返回一个根节点
	return treeObj.getNodesByFilter(function (node) {
		return node.level == 0
	}, true);
}

/**
 * 全部展开| 全部收起
 */
function expandNode(e) {
	var zTree = $.fn.zTree.getZTreeObj("menuTree");
	if (!zTree) {
		return;
	}
	var type = e.data.type;

	if (type == "expandAll") {
		zTree.expandAll(true);
	}
	if (type == "collapseAll") {
		zTree.expandAll(false);
	}
}

function init() {
	$("#expandAllBtn").bind("click", {
		type: "expandAll"
	}, expandNode);
	$("#collapseAllBtn").bind("click", {
		type: "collapseAll"
	}, expandNode);

	loadAllTemplate();

	// $('#server').combobox({
	// 	onChange: function (n, o) {
	// 		refreshAllTemplate();
	// 	}
	// });

}
var selectedNodes;
function refreshAllTemplate() {
	var zTree = $.fn.zTree.getZTreeObj("menuTree");
	if (zTree) {
		selectedNodes = zTree.getSelectedNodes();
	}
	document.getElementById("menuTree").innerHTML = "";
	loadAllTemplate();

}





/* 打开一个标签 */
function openTab(title, _url, id, icon, _closable) {
	//	 if ($("#tabs").tabs('exists', title)) {
	//		 $("#tabs").tabs('select', title);
	//		 return;
	//	 }

	var _content = "";
	/**
	 * 如果这个标题的标签存在，则选择该标签 否则添加一个标签到标签组
	 */
	var _c = _closable != false;

	var newtitle = title;
	$("#tabs").tabs('add', {
		title: newtitle,
		content: createTabContent(_url),
		closable: _c,
		id: id,
		icon: icon
	});

}

/* 生成标签内容 */
function createTabContent(url) {
	return '<iframe style="width:100%;height:100%;" scrolling="auto" frameborder="0" src="'
		+ url + '"></iframe>';
}



$(function () {
	init();

});
